<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统参数设置</span>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" tab-position="left" @tab-click="handleTabClick">
        <el-tab-pane 
          v-for="group in settingGroups" 
          :key="group.value" 
          :label="group.label" 
          :name="group.value"
        >
          <div class="tab-content">
            <el-form 
              :model="settingData[activeTab]" 
              ref="settingFormRef" 
              label-width="180px"
              v-loading="loading"
            >
              <el-form-item 
                v-for="(item, index) in settingData[activeTab]" 
                :key="item.id" 
                :label="item.name" 
                :prop="index.toString()"
              >
                <!-- 文本类型 -->
                <el-input 
                  v-if="item.type === 1" 
                  v-model="item.value" 
                  :placeholder="`请输入${item.name}`" 
                />
                
                <!-- 数字类型 -->
                <el-input-number 
                  v-else-if="item.type === 2" 
                  v-model.number="item.value" 
                  :placeholder="`请输入${item.name}`" 
                  :precision="0"
                  :step="1"
                  style="width: 100%;"
                />
                
                <!-- 布尔类型 -->
                <el-switch 
                  v-else-if="item.type === 3" 
                  v-model="item.value" 
                  :active-value="true"
                  :inactive-value="false"
                />
                
                <!-- 数组类型 -->
                <div v-else-if="item.type === 4">
                  <el-tag
                    v-for="(tag, tagIndex) in toArray(item.value)"
                    :key="tagIndex"
                    closable
                    @close="handleRemoveArrayItem(item, tagIndex)"
                    style="margin-right: 5px; margin-bottom: 5px;"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="inputVisible[item.id]"
                    ref="inputRef"
                    v-model="inputValue[item.id]"
                    style="width: 120px;"
                    size="small"
                    @keyup.enter="handleAddArrayItem(item)"
                    @blur="handleAddArrayItem(item)"
                  />
                  <el-button v-else size="small" @click="showInput(item.id)">
                    + 添加选项
                  </el-button>
                </div>
                
                <!-- 对象类型 -->
                <el-input 
                  v-else-if="item.type === 5" 
                  v-model="item.value" 
                  type="textarea" 
                  :rows="5" 
                  :placeholder="`请输入${item.name}，格式为JSON对象`" 
                />
                
                <!-- 其他类型 -->
                <el-input 
                  v-else 
                  v-model="item.value" 
                  :placeholder="`请输入${item.name}`" 
                />
                
                <div class="setting-desc" v-if="item.description">{{ item.description }}</div>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="handleSave">保存设置</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  getSettingGroups, 
  getGroupSettings, 
  batchUpdateSettings,
  getSettingTypeOptions
} from '@/api/setting'

// 设置分组
const settingGroups = ref([])
const activeTab = ref('')
const loading = ref(false)
const settingFormRef = ref(null)

// 设置数据
const settingData = reactive({})

// 数组类型设置的输入状态
const inputVisible = ref({})
const inputValue = ref({})
const inputRef = ref(null)

// 初始化获取设置分组
const initSettingGroups = async () => {
  try {
    loading.value = true
    const res = await getSettingGroups()
    if (res.data && res.data.length > 0) {
      settingGroups.value = res.data.map(item => ({
        label: item,
        value: item
      }))
      // 默认选择第一个分组
      activeTab.value = settingGroups.value[0].value
      // 获取第一个分组的设置数据
      await getSettingsByGroup(activeTab.value)
    }
  } catch (error) {
    console.error('获取设置分组失败:', error)
    ElMessage.error('获取设置分组失败')
  } finally {
    loading.value = false
  }
}

// 获取指定分组的设置
const getSettingsByGroup = async (group) => {
  if (!group) return
  
  try {
    loading.value = true
    const res = await getGroupSettings(group)
    if (res.data) {
      // 处理设置值
      res.data.forEach(item => {
        // 根据类型处理值
        if (item.type === 2) { // 数字
          item.value = Number(item.value)
        } else if (item.type === 3) { // 布尔
          item.value = item.value === 'true' || item.value === true
        } else if (item.type === 4) { // 数组
          try {
            if (typeof item.value === 'string') {
              item.value = JSON.parse(item.value)
            }
          } catch (error) {
            item.value = []
          }
        } else if (item.type === 5) { // 对象
          try {
            if (typeof item.value === 'string') {
              item.value = JSON.stringify(JSON.parse(item.value), null, 2)
            } else {
              item.value = JSON.stringify(item.value, null, 2)
            }
          } catch (error) {
            item.value = '{}'
          }
        }
      })
      
      // 设置到当前分组
      settingData[group] = res.data
    }
  } catch (error) {
    console.error(`获取${group}分组设置失败:`, error)
    ElMessage.error(`获取${group}分组设置失败`)
  } finally {
    loading.value = false
  }
}

// 处理标签点击
const handleTabClick = async () => {
  // 如果当前分组没有数据，则获取
  if (!settingData[activeTab.value]) {
    await getSettingsByGroup(activeTab.value)
  }
}

// 处理保存设置
const handleSave = async () => {
  try {
    loading.value = true
    
    // 准备要保存的数据
    const saveData = settingData[activeTab.value].map(item => {
      const result = { id: item.id }
      
      // 根据类型处理值
      if (item.type === 4) { // 数组
        result.value = JSON.stringify(toArray(item.value))
      } else if (item.type === 5) { // 对象
        try {
          // 确保是有效的JSON
          result.value = JSON.stringify(JSON.parse(item.value))
        } catch (error) {
          throw new Error(`${item.name}的值不是有效的JSON格式`)
        }
      } else {
        result.value = item.value
      }
      
      return result
    })
    
    await batchUpdateSettings(saveData)
    ElMessage.success('保存设置成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error(error.message || '保存设置失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = async () => {
  // 重新获取当前分组的设置
  await getSettingsByGroup(activeTab.value)
}

// 处理数组类型
const toArray = (value) => {
  if (Array.isArray(value)) {
    return value
  }
  
  try {
    if (typeof value === 'string') {
      return JSON.parse(value)
    }
  } catch (error) {
    // 解析失败，返回空数组
  }
  
  return []
}

// 显示输入框
const showInput = (id) => {
  inputVisible.value[id] = true
  inputValue.value[id] = ''
  
  nextTick(() => {
    inputRef.value.focus()
  })
}

// 添加数组项
const handleAddArrayItem = (item) => {
  const id = item.id
  const value = inputValue.value[id]
  
  if (value) {
    const array = toArray(item.value)
    array.push(value)
    item.value = array
  }
  
  inputVisible.value[id] = false
}

// 移除数组项
const handleRemoveArrayItem = (item, index) => {
  const array = toArray(item.value)
  array.splice(index, 1)
  item.value = array
}

// 初始化
onMounted(() => {
  initSettingGroups()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .title {
    font-size: 16px;
    font-weight: 600;
  }
}

.tab-content {
  padding: 10px 20px;
}

.setting-desc {
  color: #909399;
  font-size: 13px;
  line-height: 1.5;
  margin-top: 5px;
}

:deep(.el-tabs__item) {
  height: 50px;
  line-height: 50px;
}

:deep(.el-form-item) {
  margin-bottom: 25px;
  
  &:last-child {
    margin-bottom: 0;
  }
}
</style> 